<template>
  <div id="order" class="container">
    <div class="container-flex">
      <div class="left">
        <InputSearch @search="serarchCate" />
        <AttachmentCate ref="AttachmentCate" @update="getList" />
      </div>
      <div class="right">
        <BaseTitle :title="$t('附件列表')">
          <template #right>
            <el-button type="primary" @click="goAdd" class="el-icon-plus">
              {{ $t('添加附件') }}
            </el-button>
            <el-button @click="goAdd2" class="big-file">
              {{ $t('大文件上传') }}
            </el-button>
          </template>
        </BaseTitle>
        <div class="file-type">
          <span>{{ $t('文件类型') }}</span>
          <ButtonTab :tab-list="typeList" @change="handleClick" size="mini" />
        </div>

        <div class="file-box" ref="fileBox" v-resize="monResize">
          <ul class="file-list" v-loading="loading" v-show="orderData.length">
            <li class="file-card" v-for="item in orderData" :key="item.id">
              <div class="icon-box">
                <img src="~@/assets/icon-rar.png" alt="" v-if="item.type == 1" class="icon" />

                <BaseImg :src="item.reduce_img || item.url" alt="" :origin_img="item.src" v-else-if="item.type == 2"
                  class="img" />
                <img src="~@/assets/icon-video.png" alt="" v-else-if="item.type == 3" class="icon"
                  @click="handleCheck(item)" />
                <img src="~@/assets/icon-word.png" alt="" v-else-if="item.type == 4" class="icon" />
                <img src="~@/assets/icon-audio.png" alt="" v-else-if="item.type == 5" class="icon" />
                <el-dialog width="600px" append-to-body top="20px" :visible.sync="dialogVisible" :title="playvideoName"
                  @closed="closeDialog">
                  <video id="video" width="100%" autoplay="autoplay" :src="playvideo" :poster="playvideo"
                    controls="controls" preload>
                    {{ $t('您的浏览器不支持video标签') }}
                  </video>
                </el-dialog>
              </div>
              <h4>{{ item.name }}</h4>
              <div class="size-oper">
                <span>{{ item.size }}</span>
                <el-dropdown @command="handleCommand($event, item)" trigger="click">
                  <i class="el-icon-more"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="edit">
                      {{ $t('修改文件名') }}
                    </el-dropdown-item>
                    <el-dropdown-item command="copy" v-clipboard:copy="item.url" v-clipboard:success="onCopy"
                      v-clipboard:error="onError">
                      {{ $t('复制链接') }}
                    </el-dropdown-item>
                    <el-dropdown-item command="del">
                      {{ $t('删除') }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </li>
            <li class="file-card none" v-for="none in occupant" :key="none"></li>
          </ul>
          <div v-show="orderData.length">
            <el-button @click="getMore" class="center-btn" v-if="isMore">
              {{ $t('加载更多') }}
            </el-button>
            <el-button class="center-btn" v-else>{{ $t('没有了') }}</el-button>
          </div>
        </div>
        <el-empty v-if="orderData.length == 0"></el-empty>
      </div>
    </div>
    <BaseDialog :title="addForm.id ? $t('编辑') : $t('添加')" :dialog-show.sync="dialogShow" width="50%" class="inner">
      <el-tabs v-model="activeName2" type="card">
        <el-tab-pane :label="$t('附件上传')" name="first1">
          <el-form ref="addForm" :model="addForm" :rules="rules" class="addForm" label-position="top">
            <el-form-item :label="$t('文件')">
              <el-upload v-if="uploadSmall" ref="upload" :headers="myHeaders" class="avatar-uploader"
                :action="$store.getters.updateURL + '/attachment/uploadAndsave'" :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload" :auto-upload="true" :file-list="fileList" :multiple="true"
                :data="uploadData" style="display: inline-block">
                <el-button size="small" type="primary">
                  {{ $t('选取文件') }}
                </el-button>
              </el-upload>
              <UploadChunk v-else :dialog-show="dialogShow" />
            </el-form-item>
            <div class="btn">
              <el-button @click="dialogShow = false">
                {{ $t('取消') }}
              </el-button>
              <el-button type="primary" @click="submit()">
                {{ $t('提交') }}
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="$t('网络附件')" name="second1">
          <el-form id="urlForm" :rules="urlRules" :model="urlForm" label-position="top">
            <el-form-item :label="$t('名称')" prop="name">
              <el-input v-model="urlForm.name" />
            </el-form-item>
            <el-form-item :label="$t('附件地址')" prop="url">
              <el-input v-model="urlForm.url" />
            </el-form-item>
            <el-form-item :label="$t('描述')">
              <el-input v-model="urlForm.description" type="textarea" />
            </el-form-item>
            <div class="btn">
              <el-button @click="dialogShow = false">
                {{ $t('取消') }}
              </el-button>
              <el-button type="primary" @click="submitUrl()">
                {{ $t('提交') }}
              </el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </BaseDialog>
    <BaseDialog :title="$t('修改文件名')" :dialog-show.sync="dialogShow1" width="50%" class="inner">
      <el-form id="urlForm1" :model="urlForm1" label-position="top">
        <el-form-item class="form_item" :label="$t('名称')" prop="name">
          <el-input v-model="urlForm1.name" class="form_item_input" />
        </el-form-item>
        <el-form-item class="form_item" :label="$t('附件地址')" prop="url">
          <span>{{ urlForm1.prefix_url }}{{ urlForm1.suffix_url }}</span>
          <!-- <el-input v-model="urlForm1.suffix_url" class="form_item_input" /> -->
        </el-form-item>
        <el-form-item class="form_item" :label="$t('描述')">
          <el-input v-model="urlForm1.description" type="textarea" class="form_item_textarea" />
        </el-form-item>
        <div class="btn">
          <el-button @click="dialogShow1 = false">{{ $t('取消') }}</el-button>
          <el-button type="primary" @click="submitUrl1()">
            {{ $t('提交') }}
          </el-button>
        </div>
      </el-form>
    </BaseDialog>
  </div>
</template>
<script>
import attachmentApi from '@/api/system/attachment.js'
import systemApi from '@/api/system/system'
import websiteApi from '@/api/website.js'
import compressImg from '@/utils/compressImg'

export default {
  data() {
    return {
      isMore: true,
      loading: false,
      occupant: [],
      uploadSmall: true,
      dialogVisible: false, // 视频播放弹窗
      playvideo: null, // 存储用户点击的视频播放链接
      playvideoName: null, // 存储正在播放视频的名称
      videoName: '',
      typeList: [
        { label: this.$t('全部'), value: 0 },
        { label: this.$t('压缩包'), value: 1 },
        { label: this.$t('图片'), value: 2 },
        { label: this.$t('视频'), value: 3 },
        { label: this.$t('文档'), value: 4 },
        { label: this.$t('音频'), value: 5 }
      ],
      activeName2: 'first1',
      type: 0,
      list: [],
      myHeaders: { Authorization: `Bearer ${this.$store.getters.token}` },
      headers: {},
      siteId: this.$store.getters.siteId,
      imageUrl: '',
      imgUrl: this.$store.getters.updateURL,
      orderData: [], //
      dialogShow: false,
      dialogShow1: false,
      options: [], // 站点下拉选项
      value: '', // 站点下拉框的值
      cateList: '', // 分类列表
      fileList: [], // 文件上传列表
      addForm: {},

      rules: {},
      urlRules: {
        name: [
          {
            required: 'true',
            message: this.$t('请输入附件名称'),
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: 'true',
            message: this.$t('请输入附件地址'),
            trigger: 'blur'
          }
        ]
      },
      urlForm: {
        name: '',
        url: '',
        description: '',
        storage: 5
      },
      urlForm1: {
        id: 0,
        name: '',
        url: '',
        prefix_url: '',
        suffix_url: ''
      },
      searchForm: {
        title: ''
      },
      page: {
        total: 0,
        limit: 1,
        size: 25
      }, // 分页器
      val: {},
      id: '',
      uploadData: {
        type: 0,
        attachment_cate_id: 0
      },
      cate_id: 0,
      attachmentName: '',
      attachmentDescription: '',
      fileSize: '',
      chunkSize: '',
      offWidth: '',
      files: ''
    }
  },
  computed: {
    siteId1() {
      return this.$store.getters.siteId
    }
  },
  watch: {
    siteId1(val, value) {
      if (value) {
        this.orderData = []
        this.getList()
      }
    },
    offWidth(data) {
      const length = Math.floor(data / 200) - 2
      this.occupant = []
      for (let i = 0; i < length; i++) {
        this.occupant.push(i)
      }
    }
  },
  created() {
    this.getWebsite(this.$store.getters.siteId)
    this.getList()
    this.getUpload()
    // this.getCatelist()
  },
  mounted() {
    this.$nextTick(() => {
      this.offWidth = this.$refs.fileBox.offsetWidth
    })
  },
  methods: {
    handleCommand(type, item) {
      this.files = item
      switch (type) {
        case 'edit':
          this.edit(item)
          break
        case 'del':
          this.del(item)
          break
      }
    },
    // 监听dom变化，计算每行排列几个
    monResize() {
      this.$nextTick(() => {
        this.offWidth = this.$refs.fileBox.offsetWidth
      })
    },
    // 添加网络附件
    submitUrl() {
      const val = []
      val.push(this.urlForm)
      attachmentApi.attachmentSave(val).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.dialogShow = false
        }
      })
    },
    getWebsite(val) {
      this.options.forEach(el => {
        if (el.id == val) {
          var url = el.domain
          if (el.domain.substring(0, 2) == '--') {
            url = el.domain.substring(2, el.domain.length)
          }
          this.websiteUrl = 'http://' + url
          console.log(this.websiteUrl)
        }
      })
    },
    getUpload() {
      systemApi.sysList().then(res => {
        const data = res.data
        this.chunkSize = data[1].children[10].value * 1024
      })
    },
    // 搜索附件分类
    serarchCate(cateTitle) {
      this.$refs.AttachmentCate.getCateList(cateTitle)
    },
    // 复制到剪切板
    onCopy() {
      this.$message.success(this.$t('复制成功'))
    },
    onError() {
      this.$message.error(this.$t('复制失败'))
    },
    handleCheck(row) {
      this.playvideo = row.url // 存储用户点击的视频播放链接
      this.playvideoName = row.name // 存储用户点击的视频播放链接
      this.dialogVisible = true
      // this.videoName = this.playvideoName
    },
    closeDialog() { },
    // tab切换
    handleClick(val) {
      this.loading = true
      this.uploadData.type = val
      this.type = val
      this.orderData = []
      this.getList()
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList) {
      if (res.code == 0) {
        // this.addForm.file = file.response.data
        const arr = []
        fileList.forEach(el => {
          if (el.response) {
            arr.push(el.response.data)
          }
        })
        this.addForm.file = arr
      }
    },
    upload(row) {
      this.val.id = row.id
      this.val.title = row.title
      this.val.type = row.type
    },
    async beforeAvatarUpload(file) {
      const size = file.size * 1
      if (size >= this.chunkSize) {
        this.$message.warning(this.$t('文件过大'))
        // this.uploadSmall = false
        this.dialogShow = false
      } else {
        const url = await compressImg(file, 0.2)
        this.uploadData.reduce_img = url?.file
        return true
      }
    },

    // 批量删除
    Batchdelete() { },
    // 获取站点列表
    getWebsiteList() {
      websiteApi.websiteList().then(res => {
        this.options = res.data
      })
    },

    // 获取文件类别列表
    getCatelist() {
      attachmentApi.cateList().then(res => {
        this.cateList = res.data
      })
    },
    // 新增
    goAdd() {
      this.id = ''
      this.addForm = {}
      this.fileList = []
      this.dialogShow = true
      this.uploadSmall = true
    },
    goAdd2() {
      this.id = ''
      this.addForm = {}
      this.fileList = []
      this.dialogShow = true
      this.uploadSmall = false
    },
    edit(row) {
      this.urlForm1.id = row.id
      this.urlForm1.name = row.name
      this.urlForm1.url = row.url
      this.urlForm1.prefix_url = row.prefix_url
      this.urlForm1.suffix_url = row.suffix_url
      this.urlForm1.description = row.description
      this.dialogShow1 = true
    },
    // 编辑文件名称 提交
    submitUrl1() {
      attachmentApi.editFileUrl(this.urlForm1).then(res => {
        if (res.code == 0) {
          this.files.name = this.urlForm1.name
          this.files.description = this.urlForm1.description
          this.$message.success(res.msg)
          this.dialogShow1 = false
        }
      })
    },

    // 获取内链详情
    getInfo(val) {
      attachmentApi.innerInfo({ id: val }).then(res => {
        this.addForm = res.data
        this.dialogShow = true
      })
    },
    getAttachmentData(data) {
      this.attachmentName = data.name
      this.attachmentDescription = data.description
    },
    // 提交新增附件
    submit() {
      this.orderData = []
      this.getList()
      this.dialogShow = false
    },

    // 删除
    del(row) {
      this.$confirm(this.$t('删除该附件'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          attachmentApi.attachmentDelete({ id: row.id }).then(res => {
            if (res.code == 0) {
              this.orderData.forEach((el, index) => {
                if (el.id == row.id) {
                  this.orderData.splice(index, 1)
                  return
                }
              })
              this.$message.success(res.msg)
            }
          })
        })
        .catch(() => { })
    },
    getMore() {
      this.loading = true
      const true_total = this.val.limit * this.val.page
      if (this.page.total > true_total) {
        this.page.limit = this.page.limit + 1
        this.getList()
      }
    },
    // 列表
    getList(cate_id) {
      this.val.page = this.page.limit
      this.val.limit = this.page.size
      this.val.type = this.type
      this.val.website_id = this.$store.getters.siteId
      if (cate_id != undefined) {
        this.uploadData.attachment_cate_id = cate_id
      }
      this.val.cate_id = this.uploadData.attachment_cate_id
      attachmentApi.attachmentList(this.val).then(res => {
        this.loading = false
        if (cate_id) {
          this.page.limit = 1
          this.orderData = res.data
        } else {
          this.orderData = [...this.orderData, ...res.data]
        }
        const true_total = this.val.limit * this.val.page
        this.page.total = res.count
        if (this.page.total > true_total) {
          this.isMore = true
        } else {
          this.isMore = false
        }
      })
    }
  }
}
</script>
<style lang="scss">
#attachmentTree.el-input__inner {
  border-right: none;
}

#order {
  .inner {
    .el-select {
      width: 100%;
    }
  }

  .addForm .el-form-item__content {
    width: calc(100% - 80px);
  }

  .el-upload-list__item {
    transition: none !important;
  }
}

#urlForm.el-form--inline .el-form-item__content {
  width: calc(100% - 60px) !important;
}
</style>
<style scoped lang="scss">
.container-flex {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  padding: 0 16px 0 0;
  background-color: #fff;

  .left {
    width: 300px;
    border-right: solid 1px #eee;
    padding: 16px 16px 16px 0;
  }

  .right {
    width: calc(100% - 300px);
    padding: 16px;
  }
}

.search-input {
  padding-left: 16px;
}

.file-type {
  span {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #86909c;
    line-height: 20px;
    margin-right: 18px;
  }
}

.big-file.el-button {
  border-color: var(--huocms-com-color-primary);
  color: var(--huocms-com-color-primary);
}

.file-box {
  margin-top: 16px;

  .file-list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    margin: 0 auto;
    justify-content: space-between;

    .file-card {
      display: inline-block;
      width: 200px;
      height: 200px;
      margin-bottom: 20px;
      border: 1px solid #f3f5f8;
      box-sizing: border-box;
      border-radius: 4px;

      .icon-box {
        background-color: #f8f9fb;
        text-align: center;
        overflow: hidden;
        height: 140px;
        line-height: 140px;

        .img {
          max-width: 100%;
          max-height: 100%;
          border-radius: 4px 4px 0 0;
        }

        .icon {
          width: 64px;
          height: 64px;
          margin-top: 38px;
        }
      }

      h4 {
        padding: 9px 9px 0;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #000000;
        line-height: 21px;
      }

      .size-oper {
        padding: 0 9px;
        width: 100%;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #8291a9;
        line-height: 21px;
        display: flex;
        justify-content: space-between;

        .el-icon-more {
          color: #8291a9;
          cursor: pointer;
        }
      }
    }

    .file-card.none {
      height: 0;
      border: none;
      background-color: #f00;
      margin: 0;
    }
  }

  .center-btn {
    margin: 0 auto;
    display: block;
  }
}

#urlForm {
  .el-form-item {
    width: 100%;
  }
}

.video {
  #viddeo {
    height: 300px;
  }
}

.playIcon {
  font-size: 22px;
  cursor: pointer;
}
</style>
